import torch.nn as nn
from torch.nn import init
import torch.utils.data
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt

mnist_train = torchvision.datasets.MNIST(root='./Datasets/MNIST', train=True, download=True, transform=transforms.ToTensor())
mnist_test = torchvision.datasets.MNIST(root='./Datasets/MNIST', train=False, download=True, transform=transforms.ToTensor())

batch_size = 200
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=0)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False,num_workers=0)

num_inputs, num_outputs, num_hiddens = 784, 10, 256

class FlattenLayer(nn.Module):
    def __init__(self):
        super(FlattenLayer, self).__init__()
    def forward(self, x):
        return x.view(x.shape[0], -1)

net = nn.Sequential(
     FlattenLayer(),
     nn.Linear(num_inputs, num_hiddens),
     nn.LeakyReLU(),                          #隐藏层激活函数采用leakyrelu
     nn.Linear(num_hiddens, num_outputs),
     )

for params in net.parameters():
    init.normal_(params, mean=0, std=1)

loss = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)

def evaluate_accuracy(test_iter, net):
    acc_sum, n = 0, 0
    for X, y in test_iter:
        y_hat = net(X)
        acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
        n += y.shape[0]
    return acc_sum / n

num_epochs = 12

def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, optimizer):
    train_ls, test_ls, x_epoch = [], [], []
    for epoch in range(num_epochs):
        train_1_sum, train_acc_sum, n = 0.0, 0.0, 0
        train_1_test_sum, n_test = 0.0, 0
        for X, y in train_iter:
            y_hat = net(X)
            l = loss(y_hat, y).sum()
            optimizer.zero_grad()
            l.backward()
            optimizer.step()

            train_1_sum += l.item()
            train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
            n += y.shape[0]
        train_ls.append(train_1_sum / n)
        x_epoch.append(epoch + 1)
        test_acc = evaluate_accuracy(test_iter, net)
        print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f' % (epoch + 1, train_1_sum / n, train_acc_sum / n, test_acc))

        for X_test, y_test in test_iter:
            y_hat = net(X_test)
            l = loss(y_hat, y_test).sum()
            train_1_test_sum += l.item()
            n_test += y_test.shape[0]
        test_ls.append(train_1_test_sum / n_test)


    plt.plot(x_epoch, train_ls, label="train_loss", linewidth=2)
    plt.plot(x_epoch, test_ls, label="test_loss", linewidth=1.5)
    plt.title("leakyrelu")
    plt.xlabel("epoch")
    plt.ylabel("loss")
    plt.legend()
    plt.show()


train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, optimizer)